﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace C_高级编程
{
    internal class DataTableToList
    {
        /// <summary>
        /// 将DataTable 转化成List<>
        /// </summary>
        /// <typeparam name="T">转换后的对象类型</typeparam>
        /// <param name="dataTable">要转换的DataTable</param>
        /// <returns></returns>
        public static List<T> ToList<T>(DataTable dataTable) where T:class,new()
        { 
            List<T> list = new List<T>();

            //获取最终对象类型
            var type = typeof(T);
            //获取目标对象所有的属性
            var propertInfos = type.GetProperties();

           

            //遍历dataTable
            foreach (DataRow dataRow in dataTable.Rows)
            {
                //创建目标对象
                    T t = new T();//一定要用泛型实例化
                    //T t2 = Activator.CreateInstance(type) as T;
                //遍历当前DataRow
                foreach (var property in propertInfos)
                {
                   
                    //给当前对象的当前属性赋值
                    property.SetValue(t, dataRow[property.Name]);
                }
                list.Add(t);
            }


            return list;
        }
    }
}
